package com.example.demo.Controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/header")
public class HeaderController {

    //获取Cookie
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request){

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName() + " :  "+ cookie.getValue());


        }
        return " 成功";
    }

    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("cxk") String cxkgg,@CookieValue("lxy") String lxy1){
        return "从cookie中获取,  蔡徐坤: " + cxkgg + " 获取 :" +lxy1;
    }

    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
        //获取session对象
        HttpSession session = request.getSession();
        session.setAttribute("username", "cxk");
        session.setAttribute("age",15);
        return "设置session成功";
    }

    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request){

        HttpSession session = request.getSession();

        String username = (String) session.getAttribute("username");

        return "username:" + username;

    }

    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session){
        String username = ( String) session.getAttribute("username");
        System.out.println(session.getAttribute("age"));
        return "username:" + username;
    }

    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("username") String username){
        return "username:" + username;
    }

    @RequestMapping("/getHeader")
    public  String getHeader(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        return " UserAgent" + userAgent;
    }


    @RequestMapping("/getHeader2")
    public String header(@RequestHeader("User-Agent") String userAgent) {
        return "userAgent："+userAgent;
    }








}
